<script setup>
import api from '../api/foster_api.js'
import petApi from '../api/pet_api.js'  //下拉框
import { ref, onMounted } from 'vue';
import {
  ElIcon,
  ElTag,
  ElPopover,
  ElButton,
  ElTable,
  ElTableColumn,
  ElMessageBox,
  ElMessage,
  ElSelect, ElOption, ElInput, ElFormItem
} from 'element-plus';
import {Picture, Timer, Warning} from '@element-plus/icons-vue'; // 引入用到的图标
import lodash from 'lodash'

const petList = ref([]);
// 定义默认图片（无照片时显示）
const defaultImg = 'https://picsum.photos/100/100?grayscale'; // 灰度占位图

//声明绑定数据 （下拉框）****************
const pet_name = ref([]);

// 定义绑定的数据
// 表格中的数据
const tableData = ref([]); // 表格数据
const total = ref(0); // 总记录数
// 编辑弹窗可见性
const editWinVisible = ref(false);
// 新增弹窗可见性
const addWinVisible = ref(false);
// 查询的数据
const searchObj = ref({ // 查询条件
  current: 1,
  limit: 10,
  user_id: '',
  pet_id: '',
  pet_name: '',
  foster_date: '',
  foster_state: '',
  pet_photo: '',
})
// 编辑表单数据
const editObj = ref({
});
// 新增表单数据
const addObj = ref({// 新增表单数据
  user_id: '',
  pet_id: '',
  pet_name: '',
  foster_date: '',
  foster_state: '',
  pet_photo: '',
});

// 新增下拉框选项数据，这里假设状态值与显示文本一致，也可自定义
const StateOptions = [
  { label: '已领养', value: '已领养' },
  { label: '已寄养', value: '已寄养' },
  { label: '无', value: '无' }
];

// 获取表格数据
const search = async () => {
  const result = await api.page(searchObj.value);
  tableData.value = result.data;
  total.value = result.count;
}

// 页面加载后初始化数据
onMounted(async () => {
  search();

  pet_name.value=await petApi.all();  //下拉框***************
})

//自定义方法

// 分页
const handleSizeChange=()=>{
  console.log(searchObj);
  search();
}
// 当前页码
const handleCurrentChange=()=>{
  console.log(searchObj);
  search();
}

// 执行查询
const handlerSearch = () => {
  searchObj.value.current = 1;
  search();
  console.log(searchObj);
}

// 编辑弹窗取消
const editCancel = () => {
  editObj.value = {};
  editWinVisible.value = false;
}

// 编辑提交
const editCommit = async () => {
  await api.edit(editObj.value);
  search();
  editWinVisible.value = false;
  ElMessage.success('修改成功');
}

// 编辑操作
const handleEdit = (index, row) => {
  editObj.value = lodash.clone(row); // 克隆行数据到编辑表单
  editWinVisible.value = true;
}

// 删除操作
const handleDelete = (index, row) => {
  ElMessageBox.confirm(
      '确定要删除该行数据吗?',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(async () => {
        await api.del(row.id);// 删除数据
        search();// 重新查询
        ElMessage.success('删除成功');// 提示信息
      })
      .catch(() => {// 取消删除
        ElMessage.info('已取消删除');// 提示信息
      })
}

// 打开新增弹窗
const openAddDialog = () => {
  addObj.value = {}; // 清空新增表单
  addWinVisible.value = true;
}

// 新增提交
const addCommit = async () => {
  ElMessageBox.confirm(
      '确定要提交吗?',
      '提交提示',
      {
        confirmButtonText: '提交',
        cancelButtonText: '取消',
        type: 'info',
      }
  )
      .then(async () => {
        await api.add(addObj.value); // 提交新增表单数据
        addWinVisible.value = false;
        search();
        ElMessage.success('新增成功');
      })
      .catch(() => {
        ElMessage.info('已取消提交');
      })
};
</script>

<template>
  <!--   查询表单-->
  <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top: 10px">
    <el-form-item label="用户编号">
      <el-input v-model="searchObj.user_id" placeholder="请输入用户编号" clearable />
    </el-form-item>
    <el-form-item label="宠物名">
      <el-input v-model="searchObj.pet_name" placeholder="请输入宠物名" clearable />
    </el-form-item>
<!--    <el-form-item label="宠物编号">-->
<!--      <el-input v-model="searchObj.pet_id" placeholder="请输入宠物编号" clearable />-->
<!--    </el-form-item>-->
<!--    <el-form-item label="宠物寄养日期">-->
<!--      <el-date-picker-->
<!--          v-model="searchObj.foster_date"-->
<!--          type="date"-->
<!--          placeholder="请输入寄养时间"-->
<!--          value-format="YYYY-MM-DD"-->
<!--          clearable-->
<!--      />-->
<!--    </el-form-item>-->
    <el-form-item>
      <el-button type="primary" @click="handlerSearch">查询</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="openAddDialog">新增</el-button>
    </el-form-item>
  </el-form>
<div class="table-container">
  <el-table :data="tableData" style="width: 100%" border>
    <!-- 宠物照片列 -->
    <el-table-column label="宠物照片" width="160">
      <template #default="scope">
        <el-image
            :src="scope.row.pet_photo || defaultImg"
            fit="cover"
            style="width: 100px; height: 100px"
            :preview-src-list="[scope.row.pet_photo || defaultImg]"
            preview-teleported
            :z-index="9999"
        >
          <template #placeholder>
            <div class="image-placeholder">
              <el-icon><Picture /></el-icon>
              <span>无照片</span>
            </div>
          </template>
          <template #error>
            <div class="image-placeholder">
              <el-icon><Warning /></el-icon>
              <span>加载失败</span>
            </div>
          </template>
        </el-image>
      </template>
    </el-table-column>



    <!-- 领养日期列 -->
    <el-table-column label="寄养日期" width="180">
      <template #default="scope">
        <div style="display: flex; align-items: center">
          <el-icon><timer /></el-icon>
          <span style="margin-left: 10px">{{ scope.row.foster_date }}</span>
        </div>
      </template>
    </el-table-column>
    <!-- 宠物名称列 -->
    <el-table-column label="宠物名称" width="120">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="200">
          <template #default>
            <div>name: {{ scope.row.pet_name }}</div>
            <div>宠物宝宝的名称</div>
          </template>
          <template #reference>
            <el-tag>{{ scope.row.pet_name }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>
<!--    &lt;!&ndash; 宠物编号列 &ndash;&gt;-->
<!--    <el-table-column label="宠物编号" width="120">-->
<!--      <template #default="scope">-->
<!--        <el-popover effect="light" trigger="hover" placement="top" width="200">-->
<!--          <template #default>-->
<!--            <div>pet_id: {{ scope.row.pet_id }}</div>-->
<!--            <div>专属于宠物宝宝的身份证号</div>-->
<!--          </template>-->
<!--          <template #reference>-->
<!--            <el-tag>{{ scope.row.pet_id }}</el-tag>-->
<!--          </template>-->
<!--        </el-popover>-->
<!--      </template>-->
<!--    </el-table-column>-->
    <!-- 用户编号列 -->
    <el-table-column label="用户编号" width="120">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="200">
          <template #default>
            <div>user_id: {{ scope.row.user_id }}</div>
            <div>铲屎官的编号</div>
          </template>
          <template #reference>
            <el-tag>{{ scope.row.user_id }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>
    <!-- 用户姓名列 -->
    <el-table-column label="用户姓名" width="120">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="200">
          <template #default>
            <div>user_name: {{ scope.row.userBean.user_name }}</div>
            <div>铲屎官的姓名</div>
          </template>
          <template #reference>
            <el-tag>{{ scope.row.userBean.user_name }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>
    <!-- 领养状态列 -->
    <el-table-column label="寄养状态" width="120">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="200">
          <template #default>
            <div>领养状态: {{ scope.row.foster_state }}</div>
            <div>宠物宝宝是否被寄养</div>
          </template>
          <template #reference>
            <el-tag>{{ scope.row.foster_state }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>
    <!-- 操作列 -->
    <el-table-column label="按钮" width="120">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
          修改
        </el-button>
        <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
</div>
  <!--分页-->
  <el-pagination
      v-model:current-page="searchObj.current"
      v-model:page-size="searchObj.limit"
      :page-sizes="[1,5,10,20,30,50]"
      :background="background"
      layout="total,sizes, prev, pager, next,jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />

  <!-- 编辑对话框（独立） -->
  <el-dialog v-model="editWinVisible" title="编辑" width="500">
    <el-form :model="editObj">
      <el-form-item label="用户名" :label-width="100">
        <el-input v-model="editObj.user_id" autocomplete="off" />
      </el-form-item>
<!--      <el-form-item label="宠物编号" :label-width="100">-->
<!--        <el-input v-model="editObj.pet_id" autocomplete="off" />-->
<!--      </el-form-item>-->
      <el-form-item label="宠物名" :label-width="100">
        <el-input v-model="editObj.pet_name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="寄养日期" :label-width="100">
        <el-date-picker
            v-model="editObj.foster_date"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="寄养状态" :label-width="100">
        <el-select
            v-model="editObj.foster_state"
            placeholder="请选择领养状态"
            clearable
        >
          <el-option
              v-for="item in StateOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- 新增宠物照片输入框 -->
      <el-form-item label="宠物照片" :label-width="100">
        <el-input v-model="editObj.pet_photo" placeholder="请输入照片URL" />
        <div class="image-preview">
          <el-image
              :src="editObj.pet_photo || defaultImg"
              fit="cover"
              style="width: 100px; height: 100px; margin-top: 10px"
          />
        </div>
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editCancel">取消</el-button>
        <el-button type="primary" @click="editCommit">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 新增对话框（独立） -->
  <el-dialog v-model="addWinVisible" title="新增寄养信息" width="500">
    <el-form :model="addObj" label-width="100px">
      <el-form-item label="用户编号">
        <el-input v-model="addObj.user_id" placeholder="请输入用户编号" />
      </el-form-item>
<!--      <el-form-item label="宠物编号">-->
<!--        <el-input v-model="addObj.pet_id" placeholder="请输入宠物宝宝的编号" />-->
<!--      </el-form-item>-->
      <el-form-item label="宠物名称">
        <el-select
            v-model="addObj.pet_name"
            placeholder="请选择"
            style="width: 240px"
        >
          <el-option
              v-for="item in pet_name"
              :key="item.number"
              :label="item.pet_name"
              :value="item.pet_id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="寄养日期">
        <el-date-picker
            v-model="addObj.foster_date"
            type="date"
            placeholder="选择寄养日期"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="寄养状态">
        <el-select
            v-model="addObj.foster_state"
            placeholder="请选择领养状态"
            clearable
        >
          <el-option
              v-for="item in StateOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- 新增宠物照片输入框 -->
      <el-form-item label="宠物照片">
        <el-input v-model="addObj.pet_photo" placeholder="请输入照片URL" />
        <div class="image-preview">
          <el-image
              :src="addObj.pet_photo || defaultImg"
              fit="cover"
              style="width: 100px; height: 100px; margin-top: 10px"
          />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addWinVisible = false">取消</el-button>
        <el-button type="primary" @click="addCommit">提交新增</el-button>
      </div>
    </template>f
  </el-dialog>
</template>

<style scoped>

/* 新增：表格外层容器样式 */
.table-container {
  flex: 1; /* 让容器填充剩余空间 */
  overflow: auto; /* 内容超出时出现滚动条 */
}

/* 调整表格样式，使其在容器内正确显示 */
.el-table {
  --el-table-header-text-color: #333;
  --el-table-row-hover-bg-color: #f5f7fa;
  width: 100%; /* 确保表格宽度占满容器 */
  height: 100%; /* 确保表格高度占满容器 */
}

/* 图片占位符样式 */
.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: #f5f7fa;
  color: #909399;
}

.image-placeholder el-icon {
  font-size: 20px;
  margin-bottom: 5px;
}


/* 编辑/新增中的图片预览样式 */
.image-preview {
  margin-top: 10px;
}

</style>